const mysql = require('mysql2/promise');
require('dotenv').config();

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '123456',
  database: process.env.DB_NAME || 'uni_library',
  charset: 'utf8mb4',

  // 连接池参数（mysql2支持）
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,

  // 连接参数
  connectTimeout: 30000,

  // Keep-Alive 设置
  enableKeepAlive: true,
  keepAliveInitialDelay: 0,

  // 空闲连接控制（mysql2 >=2.3）
  maxIdle: 10,
  idleTimeout: 60000,

  // SSL配置（生产环境建议启用）
  ssl: process.env.NODE_ENV === 'production' ? {
    rejectUnauthorized: false
  } : false
});

// 测试连接
const testConnection = async () => {
  try {
    const conn = await pool.getConnection();
    console.log('✅ MySQL连接成功');
    conn.release();
  } catch (err) {
    console.error('❌ MySQL连接失败', err.message);
    process.exit(1);
  }
};

module.exports = { pool, testConnection };